#!/bin/bash
#
# Copyright (C) 2012 David Goulet <dgoulet@efficios.com>
#
# SPDX-License-Identifier: LGPL-2.1-only

TEST_DESC="UST tracer - Testing high events throughput"

CURDIR=$(dirname $0)/
TESTDIR=$CURDIR/../../..
NR_APP=20
BIN_NAME="gen-events"
SESSION_NAME="high-throughput"
EVENT_NAME="tp:tptest"
NUM_TESTS=9

source $TESTDIR/utils/utils.sh

if [ ! -x "$CURDIR/$BIN_NAME" ]; then
	BAIL_OUT "No UST nevents binary detected."
fi

TRACE_PATH=$(mktemp -d -t tmp.test_high_throughput_ust_trace_path.XXXXXX)

# MUST set TESTDIR before calling those functions

plan_tests $NUM_TESTS

print_test_banner "$TEST_DESC"

bail_out_if_no_babeltrace

start_lttng_sessiond

create_lttng_session_ok $SESSION_NAME $TRACE_PATH

enable_ust_lttng_event_ok $SESSION_NAME $EVENT_NAME
start_lttng_tracing_ok $SESSION_NAME

for i in `seq 1 $NR_APP`; do
	./$CURDIR/$BIN_NAME >/dev/null 2>&1 &
done

diag "Waiting for applications to end"
wait
pass "Wait for applications to end"

stop_lttng_tracing_ok $SESSION_NAME
destroy_lttng_session_ok $SESSION_NAME

stop_lttng_sessiond

# Validate test

TEMP_FILE=$(mktemp -t tmp.test_high_throughput_tmp_file1.XXXXXX)
TEMP_FILE_2=$(mktemp -t tmp.test_high_throughput_tmp_file2.XXXXXX)

traced=$("$BABELTRACE_BIN" $TRACE_PATH 2>/dev/null | wc -l)
"$BABELTRACE_BIN" $TRACE_PATH >/dev/null 2>$TEMP_FILE_2

cat $TEMP_FILE_2 | cut -f4 -d " " >$TEMP_FILE

dropped=0
while read line;
do
	let dropped=$dropped+$line
done < $TEMP_FILE

let total=$dropped+$traced
let wanted=$NR_APP*1000000

if [ $wanted -ne $total ]; then
	fail "Trace validation"
	diag "Expected $wanted. Dropped $dropped. Recorded $traced. Total $total"
else
	pass "Trace validation"
	diag "Expected $wanted. Dropped $dropped. Recorded $traced. Total $total"
fi

rm -rf $TRACE_PATH
rm $TEMP_FILE $TEMP_FILE_2
